package com.sum.tea.rongrui

import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Toast
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_rongrui.RrReader
import com.rfid.trans.MaskClass
import com.sum.common.base.BaseMvvmActivity
import com.sum.tea.R
import com.sum.tea.databinding.ActivityMaskBinding
import com.sum.tea.rongrui.viewmodel.MaskViewModel

class MaskActivity : BaseMvvmActivity<ActivityMaskBinding, MaskViewModel>() {

    private val strMem = arrayOf("EPC", "TID", "USER")
    private var maskData: String = ""

    override fun initView(savedInstanceState: Bundle?) {
        // 初始化 Spinner
        val spAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, strMem)
        spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        mBinding.memSpinner.adapter = spAdapter
        mBinding.memSpinner.setSelection(0, false)

        // 设置点击监听器
        mBinding.buttonAdd.setOnClickListener{
            handleAdd()
        }
        mBinding.buttonClear.setOnClickListener{
            handleClear()
        }
    }

    private fun handleAdd() {
        val addrText = mBinding.etAddr.text.toString()
        val lenText = mBinding.etLen.text.toString()
        val dataText = mBinding.etData.text.toString()

        if (addrText.isBlank() || lenText.isBlank() || dataText.isBlank()) {
            return
        }

        try {
            val maskAddr = addrText.toInt()
            val maskMem = mBinding.memSpinner.selectedItemPosition + 1
            val maskLen = lenText.toInt()
            var strData = dataText

            if (strData.length % 2 != 0) {
                strData += "0"
            }

            if (strData.length / 2 < (maskLen + 7) / 8) {
                Toast.makeText(
                    applicationContext,
                    getString(R.string.strfailed),
                    Toast.LENGTH_SHORT
                ).show()
                return
            }

            val mask = MaskClass().apply {
                MaskData = ConvertUtils.hexString2Bytes(strData)
                MaskAdr = byteArrayOf((maskAddr shr 8).toByte(), maskAddr.toByte())
                MaskLen = maskLen.toByte()
                MaskMem = maskMem.toByte()
            }

            RrReader.rrlib.AddMaskList(mask)
            val temp = "$maskMem,$maskAddr,$maskLen,$strData"
            maskData += "$temp\r\n"
            mBinding.txtMask.text = maskData
            ToastUtils.showShort(getString(R.string.strsuccess))
        } catch (ex: Exception) {
            ToastUtils.showShort(getString(R.string.strfailed))
        }
    }

    private fun handleClear() {
        maskData = ""
        mBinding.txtMask.text = ""
        RrReader.rrlib.ClearMaskList()
        ToastUtils.showShort("已清空掩码列表")
    }
}
